package org.dualr.litelog.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.dualr.litelog.entity.Link;

public class LinkDao {
	private static LinkDao _instance = null;

	public static LinkDao getInstance() {
		if (_instance == null) {
			_instance = new LinkDao();
		}
		return _instance;
	}

	public Long insert(Link link) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(link);
		} finally {
			pm.close();
		}
		return link.getId();
	}
	
	//get link by id
	public Link getById(long id){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Link link = pm.getObjectById(Link.class, id);
		return link;
		
	}
	// delete by id
	public boolean deleteById(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Link link = pm.getObjectById(Link.class, id);
		pm.deletePersistent(link);
		pm.close();
		return true;
	}

	// get all link
	@SuppressWarnings("unchecked")
	public List<Link> getAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Link.class);
		List<Link> link = null;
		try {
			link = (List<Link>) query.execute();
			return link;
		} finally {
			query.closeAll();
		}
	}
	
	//update link
	public void update(Link link) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Link l = pm.getObjectById(Link.class, link.getId());
			l.setName(link.getName());
			l.setUrl(link.getUrl());
			l.setTitle(link.getTitle());
			l.setImage(link.getImage());
			l.setCategoryId(link.getCategoryId());
		} finally {
			pm.close();
		}
	}

}
